package ucenter

import (
	"github.com/jinzhu/gorm"
	"time"
)

type WeChat struct {
	ID						int
	UID 					int 		`gorm:"index" json:"uid"`
	WeappOpenId 			string  	`json:"weapp_open_id"`
	Nickname				string  	`json:"nickname"`
	Avatar					string		`json:"avatar"`
	School					string		`json:"school"`
	CreatedAt  				time.Time 	`json:"created_at"`
	UpdatedAt  				time.Time 	`json:"updated_at"`
	DeletedAt  				*time.Time 	`json:"deleted_at"`
}

func (WeChat) TableName() string {
	return "wechats"
}

func ExistByOpenIdWeChat(open_id string, uid int) (error, *WeChat){
	chat := &WeChat{}
	err  := udb.Unscoped().Where("weapp_open_id = ? AND uid = ?", open_id, uid ).First(&chat).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return err, nil
	}
	return nil, chat
}


func UpdateWeChatDeleteAt(open_id string, uid int) error {
	if err := udb.Unscoped().Model(&WeChat{}).Where("weapp_open_id = ? AND uid = ?", open_id, uid ).Update("deleted_at", nil).Error; err != nil {
		return err
	}
	return nil
}


func AddWeChat(uid int, weapp_open_id, nickname, avatar, school string) error {
	chat := WeChat{
		UID:      			uid,
		WeappOpenId:     	weapp_open_id,
		Nickname: 			nickname,
		Avatar:				avatar,
		School:				school,
	}
	if err := udb.Create(&chat).Error; err != nil {
		return err
	}

	return nil
}

func GetWeChat (weapp_open_id string) (error, *WeChat){
	chat := &WeChat{}
	err  := udb.Select("uid, id, avatar, nickname").Where("weapp_open_id = ?", weapp_open_id).First(&chat).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return err, nil
	}
	return nil, chat
}

func DeleteWeChat (weapp_open_id string, uid int) error {
	udb.Where("weapp_open_id = ? AND uid = ?", weapp_open_id, uid).Delete(&WeChat{})
	return nil
}